package com.atguigu.tingshu.search.thred;

import com.atguigu.tingshu.common.execption.GuiguException;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ExpireThread {
    private StringRedisTemplate redisTemplate;
    //线程续期标识,volatile,保证线程间变量的可见性
    private volatile boolean isStop = false;


    public ExpireThread(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    HashMap<String, Thread> stringThreadHashMap = new HashMap<>();
    ReentrantLock reentrantLock = new ReentrantLock();
    public void expire(String lockKey, Long interval, Long ttl){
        reentrantLock.lock();
        //判断续期线程是否存在
        Thread expireThread = stringThreadHashMap.get("expire");
        if (expireThread == null){
            try {
                expireThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (!isStop) {
                            try {
                                Thread.sleep(interval);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println(Thread.currentThread().getName() + "开始续期");
                            redisTemplate.expire(lockKey, ttl, TimeUnit.SECONDS);
                        }
                    }
                });
                stringThreadHashMap.put("expire",expireThread);
                //设置续期线程为守护线程
                expireThread.setDaemon(true);
                expireThread.start();
                expireThread.setName("expire-lock-thread");
            } finally {
                reentrantLock.unlock();
            }
        }else {
            expireThread.start();
        }

    }
    public void stop(){
        isStop = true;
    }
}
